package com.newasia.management.services;/**
 * Created by mic on 2019/7/30.
 */

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.management.IManagementItemsService;
import com.newasia.management.constants.ManagementRetCode;
import com.newasia.management.converter.ItemBrandConverter;
import com.newasia.management.converter.ItemCatConverter;

import com.newasia.management.converter.ItemSpecConverter;


import com.newasia.management.converter.ItemSpuConverter;
import com.newasia.management.dal.item.entitys.*;
import com.newasia.management.dal.item.persistence.*;
import com.newasia.management.dal.user.entitys.SysMenu;
import com.newasia.management.dal.user.entitys.SysMenuExample;
import com.newasia.management.dal.user.persistence.SysMenuMapper;


import com.newasia.management.dto.productSku.*;
import com.newasia.management.dto.productSku.GetSkuDto;
import com.newasia.management.dto.productSkuPerm.ChangeSkuPermRequest;
import com.newasia.management.dto.productSkuPerm.ChangeSkuPermResponse;
import com.newasia.management.dto.productSpecValue.GetSpecValueDto;
import com.newasia.management.dto.productSpecValue.SpecValueDto;
import com.newasia.management.dto.productSpu.*;
import com.newasia.management.utils.ExceptionProcessorUtils;
import jdk.nashorn.internal.runtime.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ManagementItemsImpl implements IManagementItemsService {
    @Autowired
    ItemCatMapper itemCatMapper;

    @Autowired
    ItemCatConverter itemCatConverter;

    @Autowired
    ItemSpuMapper itemSpuMapper;


    @Autowired
    ItemSpuSpecMapper itemSpuSpecMapper;


    @Autowired
    ItemSkuMapper itemSkuMapper;

    @Autowired
    ItemSpuConverter itemSpuConverter;

    @Autowired
    ItemBrandMapper itemBrandMapper;

    @Autowired
    ItemBrandConverter itemBrandConverter;

    @Autowired
    ItemSpecMapper itemSpecMapper;

    @Autowired
    ItemSpecValueMapper itemSpecValueMapper;

    @Autowired
    ItemSpecConverter itemSpecConverter;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    ItemSkuPermMapper itemSkuPermMapper;

    @Autowired
    private RedissonClient redissonClient;












    /*********************商品**********************/
    /**
     * 创建商品--父
     * @param request
     * @return
     */
    @Override
    @Transactional
    public CreateSpuResponse createSpu(CreateSpuRequest request) {
        CreateSpuResponse response = new CreateSpuResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());


        try{
            request.requestCheck();


            ItemCatExample e=new ItemCatExample();
            e.createCriteria().andParentIdEqualTo(request.getCatId());
            long l1 = itemCatMapper.countByExample(e);
            if(l1>0){
                throw new ValidateException(
                        ManagementRetCode.CHOOSE_THREE.getCode(),
                        ManagementRetCode.CHOOSE_THREE.getMessage());
            }


            Date date = new Date();
            ItemSpu spu=new ItemSpu();
            spu.setStatus(request.getStatus()==null?0:request.getStatus());
            spu.setImage(request.getCover());
            spu.setTitle(request.getTitle());
            spu.setSellPoint(request.getSellPoint());
            spu.setCatId(request.getCatId());
            spu.setBrandId(request.getBrandId());
            spu.setAttribute(request.getAttribute());
            spu.setCreateTime(date);
            spu.setUpdateTime(date);

            itemSpuMapper.insert(spu);
            Long spuId = spu.getSpuId();
            ItemDesc des=new ItemDesc();
            des.setItemId(spuId);
            des.setItemDesc(request.getDescImg());
            des.setCreateTime(date);
            des.setUpdateTime(date);
            itemDescMapper.insert(des);

            List<List<Long>> allList=new ArrayList<>();
            for (SpuSpecDto s:request.getSpuSpecList()) {
                List<Long> item=new ArrayList<>();

                ItemSpecExample ex=new ItemSpecExample();
                ItemSpecExample.Criteria criteria = ex.createCriteria();
                criteria.andSpecNameEqualTo(s.getSpecName());
                List<ItemSpec> itemSpecs = itemSpecMapper.selectByExample(ex);
                ItemSpec spec;
                List<Long> ii=new ArrayList<>();
                if(itemSpecs.size()<=0){
                    spec=new ItemSpec();
                    spec.setStatus(1);
                    spec.setSpecName(s.getSpecName());
                    spec.setCreateTime(date);
                    spec.setUpdateTime(date);
                    itemSpecMapper.insert(spec);
                }else{
                    spec = itemSpecs.get(0);
                }
                Long specId = spec.getId();
                s.setSpecId(specId);

                for (SpecValueDto sv :s.getSpecValueList()) {
                    ItemSpecValueExample svEx=new ItemSpecValueExample();
                    ItemSpecValueExample.Criteria criteria1 = svEx.createCriteria();
                    criteria1.andSpecIdEqualTo(specId);
                    criteria1.andSpecValueEqualTo(sv.getSpecValue());
                    List<ItemSpecValue> itemSpecValues = itemSpecValueMapper.selectByExample(svEx);
                    ItemSpecValue sValue;

                    if(itemSpecValues.size()<=0){
                        sValue=new ItemSpecValue();
                        sValue.setSpecId(specId);
                        sValue.setSpecValue(sv.getSpecValue());
                        sValue.setCreateTime(date);
                        sValue.setUpdateTime(date);
                        itemSpecValueMapper.insert(sValue);
                    }else{
                        sValue=itemSpecValues.get(0);
                    }
                    Long valueId = sValue.getValueId();
                    sv.setValueId(valueId);
                    ii.add(valueId);
                    item.add(valueId);
                }


                ItemSpuSpec spsp=new ItemSpuSpec();
                spsp.setSpuId(spuId);
                spsp.setSpecId(specId);

                Collections.sort(ii);
//                ii.sort(comparator);
                spsp.setSpecValueListId(JSON.toJSONString(ii));
                spsp.setStatus(1);
                spsp.setCreateTime(date);
                spsp.setUpdateTime(date);
                itemSpuSpecMapper.insert(spsp);

                allList.add(item);
            }




            SysMenuExample sMex=new SysMenuExample();
            sMex.createCriteria().andStatusEqualTo(0);
            List<SysMenu> sysMenus = sysMenuMapper.selectByExample(sMex);


            List<List<Long>> lists = calculateCombination(allList);

            List<ItemSkuPerm >  perm=new ArrayList<>();
            List<ItemSku >  skus = new ArrayList<>();

            for (List<Long> ss:lists) {

                ItemSku sku=new ItemSku();

                sku.setStatus(0);
                List<String> images=new ArrayList<>();
                images.add(request.getCover());

                sku.setSkuImage(JSON.toJSONString(images));
                sku.setSkuSpecListId(JSON.toJSONString(ss));

                List<String> specNames=new ArrayList<>();
                for (Long l:ss) {
                    ItemSpecValue itemSpecValue = itemSpecValueMapper.selectByPrimaryKey(l);
                    specNames.add(itemSpecValue.getSpecValue());
                }

                sku.setSkuSpecListName(JSON.toJSONString(specNames));
                sku.setSpuId(spuId);
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                sku.setLimitNum(999);
                sku.setNum(999);
                sku.setSkuPrice(BigDecimal.valueOf(0));
                skus.add(sku);

//                itemSkuMapper.insertSelective(sku);

//                Long skuId = sku.getSkuId();

            }

            if(skus.size()>0){
                itemSkuMapper.insertList(skus);
                for (ItemSku sku:skus) {
                    for (SysMenu menu:sysMenus) {
                        ItemSkuPerm skuPerm=new ItemSkuPerm();
                        Double d= Double.valueOf(menu.getPerms());
                        skuPerm.setPercentage(BigDecimal.valueOf(Double.valueOf(menu.getPerms())));
                        skuPerm.setSkuId(sku.getSkuId());
                        skuPerm.setMenuId(menu.getMenuId());
                        skuPerm.setMoney(BigDecimal.valueOf(0));
                        skuPerm.setType(0);
                        perm.add(skuPerm);

//                    itemSkuPermMapper.insertSelective(skuPerm);
                    }
                }
            }

            if(perm!=null&&perm.size()>0){
                itemSkuPermMapper.insertList(perm);
            }


        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }

        return response;
    }




    public List<List<Long>> calculateCombination(List<List<Long>> inputList) {
        List<Long> combination = new ArrayList<>();

        List<List<Long>> data = new ArrayList<>();
        int n=inputList.size();
        for (int i = 0; i < n; i++) {
            combination.add((long) 0);
        }
        long i=0;
        boolean isContinue=false;
        do{
            List<Long> item= new ArrayList<>();

            //打印一次循环生成的组合
            for (int j = 0; j < n; j++) {
                item.add(inputList.get(j).get(combination.get(j).intValue()));
            }
            Collections.sort(item);
            data.add(item);

            i++;
            combination.set(n-1, i);
            for (int j = n-1; j >= 0; j--) {
                if (combination.get(j)>=inputList.get(j).size()) {
                    combination.set(j, (long) 0);
                    i=0;
                    if (j-1>=0) {
                        combination.set(j-1, combination.get(j-1)+1);
                    }
                }
            }
            isContinue=false;
            for (Long integer : combination) {
                if (integer != 0) {
                    isContinue=true;
                }
            }
        }while (isContinue);


        return  data;
    }



    /**
     * 创建商品--子
     * @param request
     * @return
     */
    @Override
    public CreateSkuResponse createSku(CreateSkuRequest request) {
        CreateSkuResponse response = new CreateSkuResponse();
        try{
            request.requestCheck();


        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 删除商品--父
     * @return
     */
    @Override
    @Transactional
    public DeleteSpuResponse deleteSpu(Long spuId) {
        DeleteSpuResponse response = new DeleteSpuResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            if (spuId!=null){
                this.generatorProduceSpecKey(spuId);

                SysMenuExample sMEx=new SysMenuExample();
                sMEx.createCriteria().andStatusEqualTo(0);
                List<SysMenu> sysMenus1 = sysMenuMapper.selectByExample(sMEx);
                clearHomepageCache();


                ItemSkuExample iskuEx=new ItemSkuExample();
                iskuEx.createCriteria().andSpuIdEqualTo(spuId);
                List<ItemSku> itemSkus = itemSkuMapper.selectByExample(iskuEx);

                for (ItemSku item:itemSkus) {
                    generatorProduceCacheKey(item.getSkuId(), (long) 0);
                    for (SysMenu menu:sysMenus1) {
                        generatorProduceCacheKey(item.getSkuId(),menu.getMenuId());
                    }
                }


                Date date = new Date();
                ItemSku data=new ItemSku();
                data.setUpdateTime(date);
                data.setStatus(2);


                ItemSkuExample e=new ItemSkuExample();
                e.createCriteria().andSpuIdEqualTo(spuId);
                itemSkuMapper.updateByExampleSelective(data,e);



//                SpuSpecExample spuSpec=new SpuSpecExample();
//                spuSpec.createCriteria().andSpuIdEqualTo(spuId);
//
//                SpuSpec d=new SpuSpec();
//                d.setStatus(2);
//                d.setUpdateTime(date);
//                spuSpecMapper.updateByExampleSelective(d, spuSpec);

                ItemSpu spu=new ItemSpu();
                spu.setSpuId(spuId);
                spu.setStatus(2);
                spu.setUpdateTime(date);
                itemSpuMapper.updateByPrimaryKeySelective(spu);
            }

        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 删除商品--子
     * @return
     */
    @Override
    public DeleteSkuResponse deleteSku(Long skuId) {
        DeleteSkuResponse response = new DeleteSkuResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{

            SysMenuExample sMEx=new SysMenuExample();
            sMEx.createCriteria().andStatusEqualTo(0);
            List<SysMenu> sysMenus1 = sysMenuMapper.selectByExample(sMEx);
            clearHomepageCache();
            generatorProduceCacheKey(skuId, (long) 0);
            for (SysMenu menu:sysMenus1) {
                generatorProduceCacheKey(skuId,menu.getMenuId());
            }



            if(skuId!=null){
                Date date = new Date();
                ItemSku data=new ItemSku();
                data.setSkuId(skuId);
                data.setUpdateTime(date);
                data.setStatus(2);

                itemSkuMapper.updateByPrimaryKeySelective(data);
            }

        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }



    /**
     * 修改商品--父
     * @return
     */
    @Override
    public ChangeSpuResponse changeSpu(Long spuId, ChangeSpuRequest request) {

        ChangeSpuResponse response = new ChangeSpuResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            if(request.getCatId()!=null){
                ItemCatExample e=new ItemCatExample();
                e.createCriteria().andParentIdEqualTo(request.getCatId());
                long l1 = itemCatMapper.countByExample(e);
                if(l1>0){
                    throw new ValidateException(
                            ManagementRetCode.CHOOSE_THREE.getCode(),
                            ManagementRetCode.CHOOSE_THREE.getMessage());
                }
            }
            //清缓存
            generatorProduceSpecKey(spuId);

            SysMenuExample sMEx=new SysMenuExample();
            sMEx.createCriteria().andStatusEqualTo(0);
            List<SysMenu> sysMenus1 = sysMenuMapper.selectByExample(sMEx);
            clearHomepageCache();

            ItemSkuExample iskuEx=new ItemSkuExample();
            iskuEx.createCriteria().andSpuIdEqualTo(spuId);
            List<ItemSku> itemSkus = itemSkuMapper.selectByExample(iskuEx);
            for (ItemSku item:itemSkus) {
                this.generatorProduceCacheKey(item.getSkuId(), (long) 0);
                for (SysMenu menu:sysMenus1) {
                    this.generatorProduceCacheKey(item.getSkuId(),menu.getMenuId());
                }

            }
            //------------------------------------




            ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(spuId);
            if(itemSpu==null){
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST_ITEM_SPU .getCode(),
                        ManagementRetCode.NOT_EXIST_ITEM_SPU .getMessage()
                );
            }
//            ItemSpu spus = itemSpuMapper.selectByPrimaryKey(spuId);

            ItemSpu data=new ItemSpu();
            Date date = new Date();
            data.setSpuId(spuId);
            data.setTitle(request.getTitle());
            data.setAttribute(request.getAttribute());
            data.setBrandId(request.getBrandId());
            data.setCatId(request.getCatId());
            data.setSellPoint(request.getSellPoint());
            data.setStatus(request.getStatus());
            data.setImage(request.getCover());
            data.setUpdateTime(date);
            itemSpuMapper.updateByPrimaryKeySelective(data);


            if(request.getDescImg()!=null) {
                ItemDesc desc = new ItemDesc();
                desc.setUpdateTime(date);
                desc.setItemId(spuId);
                desc.setItemDesc(request.getDescImg());
                itemDescMapper.updateByPrimaryKeySelective(desc);
            }

            List<SpuSpecDto> ssList =new ArrayList<>();

            for (SpuSpecDto s:request.getSpuSpecList()) {

                log.warn("----" +s.getSpecId());
                log.warn("----" +s.getSpecName());
                SpuSpecDto dt=new SpuSpecDto();

                dt.setSpecId(s.getSpecId());
                List<SpecValueDto> svList=new ArrayList<>();

                ItemSpuSpecExample itemSpuSpecExample=new ItemSpuSpecExample();
                itemSpuSpecExample.createCriteria().andSpuIdEqualTo(spuId).andSpecIdEqualTo(s.getSpecId());
                List<ItemSpuSpec> spuSpecs = itemSpuSpecMapper.selectByExample(itemSpuSpecExample);
                if(spuSpecs.size()<=0){
                    throw new ValidateException(
                            ManagementRetCode.NOT_EXIST_ITEM_SPEC .getCode(),
                            ManagementRetCode.NOT_EXIST_ITEM_SPEC .getMessage()
                    );
                }


//                dt.setSpecValueList();
//                String specValueListId = spuSpecs.get(0).getSpecValueListId();
//                JSON.parseArray()

                for (SpecValueDto dto: s.getSpecValueList()){
                    SpecValueDto svDto =new SpecValueDto();
                    ItemSpecValueExample svEx=new ItemSpecValueExample();
                    ItemSpecValueExample.Criteria criteria1 = svEx.createCriteria();
                    if(s.getSpecId()==null){
                        throw new ValidateException(
                                ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST .getCode(),
                                ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST .getMessage()
                        );
                    }
                    criteria1.andSpecIdEqualTo(s.getSpecId());

                    criteria1.andSpecValueEqualTo(dto.getSpecValue());
                    List<ItemSpecValue> itemSpecValues = itemSpecValueMapper.selectByExample(svEx);
                    ItemSpecValue sValue;

                    if(itemSpecValues.size()<=0){
                        sValue=new ItemSpecValue();
                        sValue.setSpecId(s.getSpecId());
                        sValue.setSpecValue(dto.getSpecValue());
                        sValue.setCreateTime(date);
                        sValue.setUpdateTime(date);
                        itemSpecValueMapper.insert(sValue);
                    }else{
                        sValue=itemSpecValues.get(0);
                    }




                    Long valueId = sValue.getValueId();
                    ItemSpuSpecExample issEx=new ItemSpuSpecExample();
                    issEx.createCriteria().andSpuIdEqualTo(spuId).andSpecIdEqualTo(s.getSpecId()).andSpecValueListIdLike("%"+valueId+"%");
                    List<ItemSpuSpec> itemSpuSpecs = itemSpuSpecMapper.selectByExample(issEx);

                    if(itemSpuSpecs.size()>0){
                        log.warn("itemSpuSpecs:"+itemSpuSpecs.size());
                    }else{
                        svDto.setValueId(sValue.getValueId());
                        svList.add(svDto);
                    }


                }
                dt.setSpecValueList(svList);
                ssList.add(dt);
            }


            log.warn("for 下面方法");

            SysMenuExample sMex=new SysMenuExample();
            sMex.createCriteria().andStatusEqualTo(0);
            List<SysMenu> sysMenus = sysMenuMapper.selectByExample(sMex);


            List<ItemSkuPerm >  perm=new ArrayList<>();
            List<ItemSku >  skus = new ArrayList<>();


            for (SpuSpecDto dto:ssList) {
//                log.warn(dto.getSpecId().longValue()+"");
                for (SpecValueDto svDto :dto.getSpecValueList()) {
                    ItemSpuSpecExample ex = new ItemSpuSpecExample();
                    ItemSpuSpecExample.Criteria criteria = ex.createCriteria();
                    criteria.andSpecIdEqualTo(dto.getSpecId());

                    ItemSpuSpecExample issEx = new ItemSpuSpecExample();
                    issEx.createCriteria().andSpuIdEqualTo(spuId).andSpecIdEqualTo(dto.getSpecId());
                    List<ItemSpuSpec> itemSpuSpecs = itemSpuSpecMapper.selectByExample(issEx);

                    ItemSpuSpec spec = itemSpuSpecs.get(0);
                    String specValueListId = spec.getSpecValueListId();
                    List<Long> longs = JSON.parseArray(specValueListId, Long.class);
                    longs.add(svDto.getValueId());
                    spec.setSpecValueListId(JSON.toJSONString(longs));
                    spec.setUpdateTime(date);


                    itemSpuSpecMapper.updateByPrimaryKey(spec);


                    ItemSpuSpecExample isEx = new ItemSpuSpecExample();
                    isEx.createCriteria().andSpuIdEqualTo(spuId).andSpecIdNotEqualTo(dto.getSpecId());
                    List<ItemSpuSpec> temp = itemSpuSpecMapper.selectByExample(isEx);
                    List<List<Long>> allList = new ArrayList<>();

                    for (ItemSpuSpec item : temp) {
                        allList.add(JSON.parseArray(item.getSpecValueListId(), Long.class));
                    }
                    List<List<Long>> lists = calculateCombination(allList);





                    for (List<Long> ss : lists) {
                        ItemSku sku = new ItemSku();

                        sku.setStatus(0);
                        List<String> images = new ArrayList<>();
                        images.add(request.getCover());

                        sku.setSkuImage(JSON.toJSONString(images));

                        List<Long> ls = new ArrayList<>();

                        for (Long tempDate : ss) {
                            ls.add(tempDate);
                        }
                        ls.add(svDto.getValueId());
                        sku.setSkuSpecListId(JSON.toJSONString(ls));

                        List<String> specNames = new ArrayList<>();
                        for (Long l : ss) {
                            ItemSpecValue itemSpecValue = itemSpecValueMapper.selectByPrimaryKey(l);
                            specNames.add(itemSpecValue.getSpecValue());
                        }
                        specNames.add(svDto.getSpecValue());

                        sku.setSkuSpecListName(JSON.toJSONString(specNames));
                        sku.setSpuId(spuId);
                        sku.setCreateTime(date);
                        sku.setUpdateTime(date);
                        sku.setLimitNum(999);
                        sku.setNum(999);
                        sku.setSkuPrice(BigDecimal.valueOf(0));
                        skus.add(sku);
//                        itemSkuMapper.insertSelective(sku);

//                        Long skuId = sku.getSkuId();


                    }
                    log.warn(svDto.getValueId().longValue()+"");
                }
            }


            if (skus.size()>0){
                itemSkuMapper.insertList(skus);
                for (ItemSku sku:skus) {
                    for (SysMenu menu : sysMenus) {
                        ItemSkuPerm skuPerm = new ItemSkuPerm();
                        skuPerm.setPercentage(BigDecimal.valueOf(Double.parseDouble(menu.getPerms())));
                        skuPerm.setSkuId(sku.getSkuId());
                        skuPerm.setMenuId(menu.getMenuId());
                        skuPerm.setMoney(BigDecimal.valueOf(0));
                        skuPerm.setType(0);
                        perm.add(skuPerm);
                    }
                }
            }


            log.warn(perm.size()+"++++++++");
            if(perm.size()>0){
                itemSkuPermMapper.insertList(perm);
            }


        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }

        return response;
    }


    /**
     * 修改商品--子
     * @return
     */
    @Override
    public ChangeSkuResponse changeSku(Long skuId, ChangeSkuRequest request) {

        ChangeSkuResponse response = new ChangeSkuResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{

            //清缓存
            SysMenuExample sMEx=new SysMenuExample();
            sMEx.createCriteria().andStatusEqualTo(0);
            List<SysMenu> sysMenus1 = sysMenuMapper.selectByExample(sMEx);
            clearHomepageCache();
            this.generatorProduceCacheKey(skuId, (long) 0);
            for (SysMenu menu:sysMenus1) {
                generatorProduceCacheKey(skuId,menu.getMenuId());
            }


//-----------------------


            if (skuId!=null&&skuId!=0){
                ItemSku sku =new ItemSku();
                sku.setSkuId(skuId);
                sku.setLimitNum(request.getLimitNum());
                sku.setNum(request.getNum());
                sku.setSkuPrice(request.getSkuPrice());
                if( request.getSkuImage()!=null&&request.getSkuImage().size()>0){
                    String s = JSON.toJSONString(request.getSkuImage());
                    sku.setSkuImage(s);
                }

                sku.setStatus(request.getStatus());



                Date d= new Date();
                sku.setUpdateTime(d);
                itemSkuMapper.updateByPrimaryKeySelective(sku);


                Long spuId = itemSkuMapper.selectByPrimaryKey(sku.getSkuId()).getSpuId();

                if(request.getStatus().intValue()==1){
                    ItemSpu item=new ItemSpu();
                    item.setSpuId(spuId);
                    item.setStatus(1);
                    itemSpuMapper.updateByPrimaryKeySelective(item);
                }else{
                    ItemSkuExample e= new ItemSkuExample();
                    e.createCriteria().andSpuIdEqualTo(spuId).andStatusEqualTo(1);
                    long l = itemSkuMapper.countByExample(e);
                    if(l<=0){
                        ItemSkuExample e2= new ItemSkuExample();
                        List<Integer> li=new ArrayList<>();
                        li.add(0);
                        li.add(1);
                        e2.createCriteria().andSpuIdEqualTo(spuId).andStatusIn(li);
                        long l1 = itemSkuMapper.countByExample(e2);
                        ItemSpu item=new ItemSpu();
                        item.setSpuId(spuId);
                        if(l1<=0){
                            item.setStatus(2);
                        }else{
                            item.setStatus(0);
                        }
                        itemSpuMapper.updateByPrimaryKeySelective(item);
                    }

                }

            }else if(skuId==0&&request.getList().size()>0){
                for (Long dd:request.getList()) {
                    ItemSku sku =new ItemSku();
                    sku.setSkuId(dd);
                    sku.setLimitNum(request.getLimitNum());
                    sku.setNum(request.getNum());
                    sku.setSkuPrice(request.getSkuPrice());
                    if( request.getSkuImage()!=null&&request.getSkuImage().size()>0){
                        String ss="[";
                        for (String s:request.getSkuImage()) {
                            ss=ss+"\""+s+"\"";
                        }
                        ss+="]";
                        sku.setSkuImage(ss);
                    }
                    sku.setStatus(request.getStatus());
                    Date d= new Date();
                    sku.setUpdateTime(d);
                    itemSkuMapper.updateByPrimaryKeySelective(sku);

                    ItemSku skuItem = itemSkuMapper.selectByPrimaryKey(sku.getSkuId());

                    if(skuItem.getStatus().intValue()==1){
                        ItemSpu item=new ItemSpu();
                        item.setSpuId(skuItem.getSpuId());
                        item.setStatus(1);
                        itemSpuMapper.updateByPrimaryKeySelective(item);
                    }
                }
            }else {
                throw new ValidateException(
                        ManagementRetCode.NEED_ONE_ITEM.getCode(),
                        ManagementRetCode.NEED_ONE_ITEM .getMessage()
                );
            }
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }

        return response;
    }


    /**
     * 修改代理商价格
     * @param request
     * @return
     */
    @Override
    public ChangeSkuPermResponse changeSkuPerm(ChangeSkuPermRequest request) {
//        generatorProduceCacheKey
        ChangeSkuPermResponse response = new ChangeSkuPermResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();



            for (int i = 0; i < request.getDealerIdList().size() ; i++) {
                ItemSkuPerm sp=new ItemSkuPerm();
                sp.setType(request.getType());
                sp.setMoney(BigDecimal.valueOf(request.getMoney().get(i)));
                sp.setPercentage(BigDecimal.valueOf(request.getPercentage().get(i)));
                ItemSkuPermExample ex=new ItemSkuPermExample();
                ItemSkuPermExample.Criteria criteria = ex.createCriteria();
                criteria.andSkuIdIn(request.getSkuIdList());
                criteria.andMenuIdEqualTo(request.getDealerIdList().get(i));
                itemSkuPermMapper.updateByExampleSelective(sp,ex);

            }


            //清缓存
            clearHomepageCache();
            for (Long id:request.getSkuIdList()) {
                this.generatorProduceCacheKey(id, (long) 0);
                for (Long did:request.getDealerIdList()) {
                    this.generatorProduceCacheKey(id,did);
                }
            }


        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 获取商品列表--父
     * @return
     */
    @Override
    public GetGoodListResponse getGoodList(GetGoodListRequest request) {

        GetGoodListResponse response =new GetGoodListResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            PageHelper.startPage(request.getPage(),request.getSize());

            ItemSpuExample itemSpuExample = new ItemSpuExample();
            log.info(request.toString());
            ItemSpuExample.Criteria criteria = itemSpuExample.createCriteria();

            if(request.getSpuId()!=null){
                criteria.andSpuIdEqualTo(request.getSpuId());
            }

            if(request.getCatId()!=null){
                criteria.andCatIdEqualTo(request.getCatId());
            }



            if(request.getKey()!=null){
                criteria.andTitleLike("%"+request.getKey()+"%");
            }

            if (request.getStatus()!=null&&request.getStatus().size()>0){
                List<Integer> s = request.getStatus();
                criteria.andStatusIn(s);
            }else{
                List<Integer> s = new ArrayList<>();
                s.add(0);
                s.add(1);
                criteria.andStatusIn(s);
            }

            if(request.getSort()!=null){
                itemSpuExample.setOrderByClause(request.getSort());
            }else{
                itemSpuExample.setOrderByClause("spu_id asc");
            }

            List<ItemSpu> items = itemSpuMapper.selectByExample(itemSpuExample);


            PageInfo<ItemSpu> pageInfo = new PageInfo<>(items);

            response.setTotal(pageInfo.getTotal());
            List<GoodDto> goodDtos=new ArrayList<>();
            for (ItemSpu itemSpu:items) {

                GoodDto goodDto = getGoodDetail(itemSpu, itemSpu.getSpuId());
                goodDtos.add(goodDto);
            }


            response.setItemSupDtos(goodDtos);




        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }





    /**
     * 获取商品--父
     * @return
     */
    @Override
    public GetGoodResponse getGood(Long spuId) {
        GetGoodResponse response = new GetGoodResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{

            if(spuId !=null){
                ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(spuId);
                GoodDto goodDto=getGoodDetail(itemSpu,spuId);

                response.setGood(goodDto);
            }
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }

        return response;
    }


    /**
     * 获取商品--父--单个
     * @return
     */
    private GoodDto getGoodDetail(ItemSpu itemSpu, Long spuId) {
        GoodDto goodDto = itemSpuConverter.item2good(itemSpu);

        ItemBrand itemBrand = itemBrandMapper.selectByPrimaryKey(goodDto.getBrandId());
        goodDto.setBrandName(itemBrand.getBrandName());

        ItemCat itemCat = itemCatMapper.selectByPrimaryKey(goodDto.getCatId());
        goodDto.setCatName(itemCat.getCatName());


        List<SpuSpecDto> spuSpecList=new ArrayList<>();


        ItemSpuSpecExample ssex = new ItemSpuSpecExample();
        ItemSpuSpecExample.Criteria criteria = ssex.createCriteria();
        criteria.andSpuIdEqualTo(spuId);
        List<ItemSpuSpec> itemSpuSpecs = itemSpuSpecMapper.selectByExample(ssex);
        for (ItemSpuSpec item:itemSpuSpecs) {
            ItemSpec itemSpec = itemSpecMapper.selectByPrimaryKey(item.getSpecId());

            SpuSpecDto dto=new SpuSpecDto();
            dto.setSpecName(itemSpec.getSpecName());
            dto.setSpecId(itemSpec.getId());


            List<SpecValueDto> child =new ArrayList<>();

            List<Long> longs = JSON.parseArray(item.getSpecValueListId(), Long.class);
            for (Long l:longs) {
                ItemSpecValue itemSpecValue = itemSpecValueMapper.selectByPrimaryKey(l);
                SpecValueDto specValueDto=new SpecValueDto();
                specValueDto.setValueId(l);
                specValueDto.setSpecValue(itemSpecValue.getSpecValue());
                child.add(specValueDto);
            }

            dto.setSpecValueList(child);

            spuSpecList.add(dto);

        }
        goodDto.setSpuSpecList(spuSpecList);

        ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(spuId);
        goodDto.setDescImg(itemDesc.getItemDesc());

        return goodDto;
    }


    /**
     * 获取商品列表-子
     * @return
     */
    @Override
    public GetSkuListResponse getSkuList(GetSkuListRequest request) {
        GetSkuListResponse response = new GetSkuListResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(request.getSpuId());
            if(itemSpu==null){
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST_ITEM_SPU.getCode(),
                        ManagementRetCode.NOT_EXIST_ITEM_SPU.getMessage()
                );
            }


            ItemSkuExample example = new ItemSkuExample();
            ItemSkuExample.Criteria criteria1 = example.createCriteria();
            if(request.getSpuId()!=null){
                criteria1.andSpuIdEqualTo(request.getSpuId());
            }

            if(request.getStatus()!=null&&request.getStatus().size()>0){
                criteria1.andStatusIn(request.getStatus());
            }else{

                List<Integer> s = new ArrayList<>();
                s.add(0);
                s.add(1);
                criteria1.andStatusIn(s);
            }



            if (request.getKey()!=null&&request.getKey()!=""){
                criteria1.andSkuSpecListNameLike("%"+request.getKey()+"%");
            }




            List<ItemSku> itemSku = itemSkuMapper.selectByExampleWithBLOBs(example);
            List<GetSkuDto> skuDtos =new ArrayList<>();
            for (ItemSku item:itemSku) {
                GetSkuDto skuDto = new GetSkuDto();
                skuDto.setSkuId(item.getSkuId());
                skuDto.setNum(item.getNum());
                skuDto.setLimitNum(item.getLimitNum());
                skuDto.setSkuPrice(item.getSkuPrice());
                skuDto.setSpuId(item.getSpuId());
                skuDto.setStatus(item.getStatus());
                skuDto.setCreateTime(item.getCreateTime());
                skuDto.setUpdateTime(item.getUpdateTime());
                skuDto.setSkuImage(JSON.parseArray(item.getSkuImage(),String.class));

                skuDto.setSpuTitle(itemSpu.getTitle());


                List<GetSpecValueDto> list=new ArrayList<>();

                List<Long> longs = JSON.parseArray(item.getSkuSpecListId(), Long.class);
                List<String> strings = JSON.parseArray(item.getSkuSpecListName(), String.class);
                if(longs.size()==strings.size()){
                    for (int i = 0; i <longs.size() ; i++) {


                        GetSpecValueDto d=new GetSpecValueDto();
                        d.setValueId(longs.get(i));
                        d.setSpecValue(strings.get(i));

                        ItemSpuSpecExample ex=new ItemSpuSpecExample();
                        ex.createCriteria().andSpuIdEqualTo(request.getSpuId());
                        List<ItemSpuSpec> itemSpuSpecs = itemSpuSpecMapper.selectByExample(ex);
                        for (ItemSpuSpec itemSS:itemSpuSpecs) {
                            List<Long> longs1 = JSON.parseArray(itemSS.getSpecValueListId(), Long.class);
                            if (longs1.contains(longs.get(i))){
                                d.setSpecId(itemSS.getSpecId());
                                ItemSpec itemSpec = itemSpecMapper.selectByPrimaryKey(itemSS.getSpecId());
                                d.setSpecName(itemSpec.getSpecName());
                            }

                        }
                        list.add(d);
                    }
                }
                ItemSkuPermExample spEx=new ItemSkuPermExample();
                spEx.createCriteria().andSkuIdEqualTo(item.getSkuId());
                List<ItemSkuPerm> itemSkuPerms = itemSkuPermMapper.selectByExample(spEx);
                List<SkuPermDto> ispList=new ArrayList<>();
                for (ItemSkuPerm isp:itemSkuPerms) {
                    SkuPermDto ispDto =new SkuPermDto();
                    ispDto.setId(isp.getId());
                    ispDto.setDelerId(isp.getMenuId());
                    ispDto.setMoney(isp.getMoney());
                    ispDto.setPercentage(isp.getPercentage());
                    ispDto.setType(isp.getType());
                    SysMenu menu = sysMenuMapper.selectByPrimaryKey(isp.getMenuId());
                    ispDto.setDelerName(menu.getMenuName());
                    ispList.add(ispDto);
                }


                skuDto.setPermsList(ispList);
                skuDto.setSpecValueList(list);


                skuDtos.add(skuDto);
            }




            response.setData(skuDtos);


        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }

        return response;
    }

    @Override
    public ShelvesSpuListResponse updateShelvesSpuList(ShelvesSpuListRequest request) {
        ShelvesSpuListResponse response = new ShelvesSpuListResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());

        try {
            List<Long> spuIds =  request.getSpuIds();
            switch (request.getStatus()){
                case 0:
                    for (Long spuId:spuIds) {
                        ItemSpu spu = new ItemSpu();
                        spu.setSpuId(spuId);
                        spu.setStatus(0);
                        itemSpuMapper.updateByPrimaryKeySelective(spu);
                        ItemSku sku = new ItemSku();
                        sku.setStatus(0);
                        ItemSkuExample example = new ItemSkuExample();
                        example.createCriteria().andSpuIdEqualTo(spuId).andStatusEqualTo(1);
                        itemSkuMapper.updateByExampleSelective(sku,example);
                    }
                    return response;
                case 1:
                    for (Long spuId:spuIds) {
                        ItemSpu spu = new ItemSpu();
                        spu.setSpuId(spuId);
                        spu.setStatus(1);
                        itemSpuMapper.updateByPrimaryKeySelective(spu);
                    }
                    return response;
                case 2:
                    for (Long spuId:spuIds) {
                        ItemSpu spu = new ItemSpu();
                        spu.setSpuId(spuId);
                        spu.setStatus(2);
                        itemSpuMapper.updateByPrimaryKeySelective(spu);
                        ItemSku sku = new ItemSku();
                        sku.setStatus(2);
                        ItemSkuExample example = new ItemSkuExample();
                        example.createCriteria().andSpuIdEqualTo(spuId);
                        itemSkuMapper.updateByExampleSelective(sku,example);
                    }
                    return response;
            }
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.updateShelvesSpuList occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    private void generatorProduceCacheKey(Long skuiId,Long menuId){
        StringBuilder stringBuilder=new StringBuilder("product_item");
        stringBuilder.append(":").append(skuiId);
        stringBuilder.append("-").append(menuId);
        RBucket rBucket = redissonClient.getBucket(stringBuilder.toString());
        rBucket.expire(0, TimeUnit.DAYS);
    }

    private void generatorProduceSpecKey(Long spuId){
        StringBuilder stringBuilder=new StringBuilder("product_spec");
        stringBuilder.append(":").append(spuId);
        RBucket rBucket = redissonClient.getBucket(stringBuilder.toString());
        rBucket.expire(0, TimeUnit.DAYS);
    }

    private void clearHomepageCache(){
        SysMenuExample ex=new SysMenuExample();
        ex.createCriteria().andStatusEqualTo(0);
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(ex);
        List<String> data=new ArrayList<>();
        for (SysMenu s:sysMenus) {
            data.add(s.getMenuId().longValue()+"");
        }
        data.add("null");
        data.add("0");

        for (String s:data) {
            StringBuilder home_page=new StringBuilder("home_page");
            StringBuilder home_page_nav=new StringBuilder("home_page_nav");

            home_page.append(":").append(s);
            home_page_nav.append(":").append(s);
            RBucket rBucket = redissonClient.getBucket(home_page.toString());
            rBucket.expire(0, TimeUnit.DAYS);

            RBucket bucket = redissonClient.getBucket(home_page_nav.toString());
            bucket.expire(0, TimeUnit.DAYS);
        }
        RBucket product_cate=redissonClient.getBucket("product_cate");
        product_cate.expire(0, TimeUnit.DAYS);
    }


}